#include <adc.hpp>

#if defined(CONFIG_TAR4ESP32)
const adc_channel_t ADC1_CHANNELS[] = { ADC_CHANNEL_3, ADC_CHANNEL_4, ADC_CHANNEL_5, ADC_CHANNEL_6, ADC_CHANNEL_7 };
const adc_channel_t ADC2_CHANNELS[] = { ADC_CHANNEL_0 };
#endif

ADC::ADC(int adc, int* chs, int size)
{
#if defined(CONFIG_TAR4ESP32)
	if (adc == E_ADC1)
	{
		memset(&init_config1, 0, sizeof(adc_oneshot_unit_init_cfg_t));
		memset(&config1, 0, sizeof(adc_oneshot_chan_cfg_t));
		init_config1.unit_id  = ADC_UNIT_1;
		init_config1.ulp_mode = ADC_ULP_MODE_DISABLE;
		config1.atten		  = ADC_ATTEN_DB_12;
		config1.bitwidth	  = ADC_BITWIDTH_DEFAULT;
		adc_oneshot_new_unit(&init_config1, &adc1_handle);
		for (int i = 0; i < size && i < sizeof(ADC1_CHANNELS) / sizeof(adc_channel_t); i++)
		{
			adc_oneshot_config_channel(adc1_handle, ADC1_CHANNELS[chs[i]], &config1);
		}
	}
	else if (adc == E_ADC2)
	{
		memset(&init_config2, 0, sizeof(adc_oneshot_unit_init_cfg_t));
		memset(&config2, 0, sizeof(adc_oneshot_chan_cfg_t));
		init_config2.unit_id  = ADC_UNIT_2;
		init_config2.ulp_mode = ADC_ULP_MODE_DISABLE;
		config2.atten		  = ADC_ATTEN_DB_12;
		config2.bitwidth	  = ADC_BITWIDTH_DEFAULT;
		adc_oneshot_new_unit(&init_config2, &adc2_handle);
		for (int i = 0; i < size && i < sizeof(ADC2_CHANNELS) / sizeof(adc_channel_t); i++)
		{
			adc_oneshot_config_channel(adc2_handle, ADC2_CHANNELS[chs[i]], &config2);
		}
	}

#endif
}

ADC::~ADC()
{
}

int ADC::Transfer(uint16_t& result, int adc, int channel)
{
	int adc_raw = 0;

#if defined(CONFIG_TAR4ESP32)
	if (adc == E_ADC1)
	{
		adc_oneshot_read(adc1_handle, ADC1_CHANNELS[channel], &adc_raw);
	}
	else if (adc == E_ADC2)
	{
		adc_oneshot_read(adc2_handle, ADC2_CHANNELS[channel], &adc_raw);
	}
#endif

	result = adc_raw;
	return 0;
}